package main

import (
	"encoding/json"
	"fmt"
	"html"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"runtime"
	"strings"
	"time"
)

type Server struct {
	ServerName string
	ServerIP   string
}

type Serverslice struct {
	Servers   []Server
	ServersID string
}

func PostServer(w http.ResponseWriter, req *http.Request) {
	// req.ParseForm()

	/*fmt.Printf("Request Method = ", req.Method)
	result, _ := ioutil.ReadAll(req.Body)
	req.Body.Close()
	fmt.Printf("%s\n", result)*/

	//取出参数
	queryForm, err := url.ParseQuery(req.URL.RawQuery)
	var requestParam string = ""
	if err == nil && len(queryForm["name"]) > 0 {
		requestParam = queryForm["name"][0]
		fmt.Printf("requestParam = ", requestParam)
	}
	fmt.Fprintf(w, "Hello, "+requestParam)
}

func GetServer(w http.ResponseWriter, req *http.Request) {
	fmt.Fprintf(w, "hello")
}

func WebServer(w http.ResponseWriter, r *http.Request) {
	r.ParseForm() //解释参数，默认不解释
	fmt.Fprintf(w, "Hello %s\n", html.EscapeString(r.URL.Path[1:]))
	method := r.Method
	fmt.Printf("Reqest Method is %s\n", method)

	if method == "GET" {
		fmt.Printf("usernaem = %s, password = %s\n", r.Form["username"], r.Form["password"])
		for k, v := range r.Form {
			fmt.Printf(" Request Form Param : Key=%s, Value=%s\n", k, strings.Join(v, ""))
		}
	} else if method == "POST" {
		result, _ := ioutil.ReadAll(r.Body)
		r.Body.Close()
		fmt.Printf("%s\n", result)

		//未知类型的处理方法（推荐）
		var f interface{}
		json.Unmarshal(result, &f)
		m := f.(map[string]interface{})

		for k, v := range m {
			switch vv := v.(type) {
			case string:
				fmt.Println(k, "is string ", vv)
			case int:
				fmt.Println(k, "is int ", vv)
			case float64:
				fmt.Println(k, "is float64 ", vv)
			case []interface{}:
				fmt.Println(k, " is an array ")
				for i, u := range vv {
					fmt.Println(i, u)
				}
			default:
				fmt.Println(k, " is of a type I don't know how to handle")
			}
		}

		//结构已知，解析到结构体

		var s Serverslice
		json.Unmarshal([]byte(result), &s)

		fmt.Println(s.ServersID)

		for i := 0; i < len(s.Servers); i++ {
			fmt.Println(s.Servers[i].ServerName)
			fmt.Println(s.Servers[i].ServerIP)
		}

	}
}

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	http.HandleFunc("/server/post", PostServer)
	http.HandleFunc("/server/get", GetServer)
	http.HandleFunc("/server", WebServer)
	t := time.Now()
	fmt.Println(time.Now().Format(time.ANSIC))
	// fmt.Printf("[%4d-%02d-%02d %02d:%02d:%02d] Server Start ...\n", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second())
	err := http.ListenAndServe("127.0.0.1:8082", nil)
	if err != nil {
		log.Fatal("ListenAndServe:", err.Error)
	}
}
